<template>
  <div class="main-container">
    <div>
      <el-form inline>
        <el-form-item>
          <el-input v-model="noticeNumber" class="w200" placeholder="输入通知单号进行精确查询"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="searchNotice">查看</el-button>
          <el-button @click="searchAllRunningNotice">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 生产通知卡片列表 -->
    <div id="noticeCardsPanel" class="notice-cards-panel">
      <template v-for="(notice, index) in noticeList">
        <div class="notice-card" :key="notice.noticeNumber" @click="showNoticeDetail(notice, index)"
          :style="backColors[index]">
          <el-progress type="dashboard" :percentage="notice.percent" color="#1989fa" class="mt20"
            :width="75"></el-progress>
          <p class="text">
            <b>{{ notice.noticeNumber }}</b>
          </p>
          <p class="text">{{ notice.workingNumber }}</p>
          <p class="text">{{ notice.orderUnit }}</p>
        </div>
      </template>
    </div>

    <div>
      <!-- 通知单备注 -->
      <el-input type="textarea" style="margin: 10px 0" autosize v-model="choosedNotice.remark" readonly></el-input>
      <!-- 通知单操作按钮 -->
      <div class="mb10">
        <el-button size="small" type="primary"
          v-if="!isEditing && $checkAuth('加工产品BOM设计') && choosedNotice.noticeId !== 0" @click="edit()">编辑</el-button>
        <el-button type="primary" size="small" icon="el-icon-download" @click="exportNotice()"
          v-if="!isEditing && $checkAuth('导出销售产品通知单') && choosedNotice.noticeId !== 0">导出</el-button>
        <el-button size="small" type="primary" v-if="isEditing" @click="save()">保存</el-button>
        <el-button size="small" v-if="isEditing" @click="cancel()">取消</el-button>


        <!-- TODO 权限设定 -->
        <el-button size="small" type="text" icon="el-icon-download" v-if="isEditing && $checkAuth('加工产品BOM设计')"
          @click="downloadFile()">模板下载</el-button>
        <el-upload v-if="isEditing && $checkAuth('加工产品BOM设计')" class="upload-demo" :http-request="uploadFile"
          accept=".xls" auto-upload show-file-list :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary" class="mt10 mr20">导入</el-button>
          <span slot="tip" class="el-upload__tip">只能上传xls文件,且不超过500kb</span>
        </el-upload>
      </div>
      <!-- 通知单产品显示视图 -->
      <el-table border :data="pageProductList" v-if="!isEditing" :row-class-name="tableRowClassName"
        :cell-class-name="tableCellClassName" row-key="producingId" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column align="center" width="50"></el-table-column>
        <el-table-column prop="sequenceId" label="序列号" align="center" width="70"></el-table-column>
        <el-table-column prop="state" label="状态" align="center" width="120"></el-table-column>
        <el-table-column prop="drawingNumber" label="图号" align="center" width="180"></el-table-column>
        <el-table-column prop="productName" label="品名" align="center" width="150"></el-table-column>
        <el-table-column prop="materialQuality" label="材质" align="center" width="150"></el-table-column>
        <el-table-column prop="number" label="数量" align="center" width="75"></el-table-column>
        <el-table-column prop="deliveryDate" label="交货日期" sortable align="center" width="150"></el-table-column>
        <el-table-column prop="finishedNumber" label="完工" align="center" width="75"></el-table-column>
        <el-table-column prop="workingNumber" label="在产" align="center" width="75"></el-table-column>
        <el-table-column prop="pendingNumber" label="待处理" align="center" width="75"></el-table-column>
        <el-table-column prop="waitingNumber" label="未投产" align="center" width="75"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center" min-width="100"></el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="200" v-if="$checkAuth('工艺路线投产提交')">
          <template slot-scope="scope">
            <el-button :id="bindRowId(scope.row)" size="mini" type="primary"
              @click="onClickDesign(scope.row, '产品通知')">工艺设计</el-button>
            <el-button @click="showDispatch(scope.row)" type="primary" size="small">查看派工</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 通知单产品编辑视图 -->
      <el-table border :row-class-name="tableRowClassName" :cell-class-name="tableCellClassName" :data="pageProductList"
        v-if="isEditing" row-key="producingId" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column align="center" width="50"></el-table-column>
        <el-table-column prop="sequenceId" label="序列号" align="center" width="110">
          <template slot-scope="scope">
            <span v-if="scope.row.parentId == 0">{{ scope.row.sequenceId }}</span>
            <el-input v-else class="w175" v-model="scope.row.sequenceId"
              :readonly="scope.row.state != '工艺设计'"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="drawingNumber" label="图号" align="center" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.parentId == 0">{{ scope.row.drawingNumber }}</span>
            <el-input v-else class="w175" v-model="scope.row.drawingNumber"
              :readonly="scope.row.state != '工艺设计'"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="品名" align="center" width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.parentId == 0">{{ scope.row.productName }}</span>
            <el-input v-else v-model="scope.row.productName" :readonly="scope.row.state != '工艺设计'"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="materialQuality" label="材质" align="center" width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.parentId == 0">{{ scope.row.materialQuality }}</span>
            <el-input v-else v-model="scope.row.materialQuality" :readonly="scope.row.state != '工艺设计'"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="number" label="数量" align="center" width="105">
          <template slot-scope="scope">
            <span v-if="scope.row.parentId == 0">{{ scope.row.number }}</span>
            <el-input v-else :id="'iptB3Number' + scope.row.producingId" v-model="scope.row.number" type="number"
              min="0"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryDate" label="交货日期" sortable align="center" width="120"></el-table-column>
        <el-table-column prop="finishedNumber" label="完工" align="center" width="70"></el-table-column>
        <el-table-column prop="workingNumber" label="在产" align="center" width="70"></el-table-column>
        <el-table-column prop="pendingNumber" label="待处理" align="center" width="75"></el-table-column>
        <el-table-column prop="waitingNumber" label="未投产" align="center" width="75"></el-table-column>
        <el-table-column prop="state" label="状态" align="center" width="120"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center" min-width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.parentId == 0">{{ scope.row.remark }}</span>
            <el-input v-else :id="'iptB3Number' + scope.row.producingId" v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="操作" align="center" fixed="right" width="150"
          v-if="$checkAuth('加工产品BOM设计')">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="addProduct(scope.row)"
              v-if="scope.row.parentId == 0">添加</el-button>
            <el-button size="mini" type="primary" @click="copyChildren(scope.row)"
              v-if="scope.row.parentId == 0">复制</el-button>
            <el-button size="mini" type="danger" @click="deleteProduct(scope.row)"
              v-if="scope.row.parentId > 0 && scope.row.state == '工艺设计'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { namespace } from 'vuex-class'
import { Message, Notification } from 'element-ui'
import { designProduct, uploadFile2 } from '@/api/notice'
import Layout from '@/views/_common/Layout.vue'

import _ from 'lodash'

const vuexProcess = namespace('TwoProcess')
const vuexNotice = namespace('NewNotice')
const vuexEnter = namespace('TwoEnter')

@Component({
  components: {
    Layout
  }
})
export default class Index extends Vue {
  // 获取已审批未完工的通知单
  @vuexEnter.Action GET_PROCESS_NOTICE: any
  @vuexEnter.State noticeList: any

  // 点击【设计】按钮对应的产品信息
  @vuexProcess.State designRowId: any
  @vuexProcess.State productOnDesignVersion: any
  @vuexProcess.Mutation SET_PRODUCT_ON_DESIGN_VERSION: any
  @vuexProcess.Mutation setDesignRowId: any

  @vuexNotice.Action GET_NOTICE_DETAIL: any
  @vuexNotice.State productList: any
  pageProductList: any = []
  tempProductList: [] = []

  currentNoticeId: number = 0

  // 提交请求的子产品
  subProduct: any = []

  // 通知单卡片选中时背景颜色改变
  backColors: any = []

  // 视图控制：编辑添加子产品
  isEditing: boolean = false

  // 通知单查询条件
  noticeNumber: string = ''
  // 查询具体通知单情况
  searchNotice() {
    this.GET_PROCESS_NOTICE({ noticeNumber: this.noticeNumber })
  }
  searchAllRunningNotice() {
    this.noticeNumber = ''
    this.GET_PROCESS_NOTICE({ noticeNumber: this.noticeNumber })
  }

  /**
   * 生命周期函数
   * 查询生产通知列表
   */
  created() {
    let from = this.$route.params.from
    this.GET_PROCESS_NOTICE({ noticeNumber: this.noticeNumber }).then(() => {
      console.log('获取数据完毕')
      if (from == 'back') {
        let id = this.$route.params.noticeId
        console.log('跳转到对应：' + id)
        // 打开对应通知单
        for (let i = 0; i < this.noticeList.length; i++) {
          if (this.noticeList[i].noticeId == id) {
            this.choosedNotice = this.noticeList[i]
            this.choosedNoticeIndex = i
            break
          }
        }
        this.showNoticeDetail(this.choosedNotice, this.choosedNoticeIndex)
      }
    })
  }

  bindRowId(row: any) {
    // console.log('绑定产品行设计按钮的ID')
    // console.log(row.drawingNumber)
    // console.log('绑定的ID：')
    let btnId = 'btnC2' + this.currentNoticeId + '-' + row.drawingNumber
    // console.log(btnId)
    return btnId
  }

  // 生产通知卡片信息
  choosedNotice: any = {
    noticeId: 0,
    remark: '备注'
  }
  choosedNoticeIndex: number = 0

  // 可以变更设计的产品状态
  canDesignState: any[] = ['工艺设计', '待派工', '生产中', '工艺变更设计']

  /**
   * 点击通知单卡片 显示产品详情
   */
  showNoticeDetail(data, index) {
    if (this.isEditing) {
      Notification.warning('正在编辑状态，请先保存或取消')
      return
    }
    // 调整选中卡片的背景
    this.backColors = []
    for (let i = 0; i < this.noticeList.length; i++) {
      let color = i == index ? '#ADD8E6' : '#fff'
      this.backColors.push('background-color:' + color + ';')
    }
    // 绑定选中卡片的数据
    this.choosedNotice = _.cloneDeep(data)
    this.choosedNoticeIndex = index
    // 获取产品信息
    this.getProductList(data.noticeId).then(() => {
      // 获取产品数据后滚动到设计工艺的产品行
      console.log('获取产品信息完毕，准备滚动到指定产品位置')
      console.log('指定产品：' + this.designRowId)

      const rows = document.getElementById(this.designRowId)
      console.log(rows)

      if (rows) {
        console.log('开始滚动')
        rows.scrollIntoView()
        console.log('结束滚动')
      }
    })
  }
  async getProductList(noticeId) {
    let res = await this.GET_NOTICE_DETAIL({ noticeId: noticeId })
    if (res) {
      this.pageProductList = this.productList
    }
  }

  /**
   * 点击编辑按钮
   * 修改视图状态
   * 备份产品信息
   */
  edit() {
    this.tempProductList = _.cloneDeep(this.productList)
    this.isEditing = true
  }

  /**
   * 点击下载模板文件按钮
   */
  downloadFile() {
    window.open('/product/design/import/template')
  }

  /**
   * 点击文件上传按钮
   */
  async uploadFile(event) {
    console.log(event)
    console.log(event.file)
    await uploadFile2(event.file)
      .then(res => {
        console.log(res)
        console.log(res.data)
        for (let i = 0; i < res.data.length; i++) {
          // 如果产品对象的序列号不包括'-'认为不是拆分的零部件
          let product = res.data[i]
          let idx = product['sequenceId'].indexOf('-')
          if (idx > 0) {
            let pId = product['sequenceId'].substring(0, idx)
            // 需要绑定不同的producingId
            let now = new Date()
            let id = now.getMilliseconds() + now.getSeconds() * 1000 + now.getMinutes() * 100000
            now.getFullYear

            product['producingId'] = -id
            product['typeProduct'] = '加工'
            product['state'] = '工艺设计'

            for (let i = 0; i < this.pageProductList.length; i++) {
              if (this.pageProductList[i].sequenceId == pId) {
                product['parentId'] = this.pageProductList[i].producingId
                product['noticeId'] = this.pageProductList[i].noticeId
                this.pageProductList[i].children.splice(this.pageProductList[i].children.length, 0, product)
                break
              }
            }
          }
        }
      })
      .catch(e => {
        console.log(e)
        Notification.error('上传失败')
      })
  }
  fileList: any = []
  handleRemove(file, fileList) {
    console.log(file, fileList)
  }
  handlePreview(file) {
    console.log(file)
  }
  handleExceed(files, fileList) {
    this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
  }
  beforeRemove(file, fileList) {
    return this.$confirm(`确定移除 ${file.name}？`)
  }

  /**
   * 点击取消按钮
   * 修改视图状态
   * 恢复备份产品信息
   */
  cancel() {
    this.pageProductList = this.tempProductList
    this.isEditing = false
  }

  /**
   * 点击保存按钮
   * 保存添加产品信息
   */
  save() {
    this.subProduct = []
    for (let i = 0; i < this.pageProductList.length; i++) {
      if (this.pageProductList[i].children.length > 0) {
        this.subProduct = this.subProduct.concat(this.pageProductList[i].children)
      }
    }

    // 参数校验结果
    let paramValid = true
    // 产品校验
    for (let i = 0; i < this.subProduct.length; i++) {
      let product = this.subProduct[i]
      if (product.drawingNumber == null || product.drawingNumber == '') {
        Notification.warning('产品图号不能为空')
        paramValid = false
      }
      //   if (product.number < product.workingNumber + product.finishedNumber) {
      //     Notification.warning(product.drawingNumber + '产品数量不能少于已生产数量')
      //     paramValid = false
      //   }
    }

    // 输入图号/品名/材质不能包含空格
    for (var i = 0; i < this.subProduct.length; i++) {
      let drawingNumber = this.subProduct[i].drawingNumber
      let productName = this.subProduct[i].productName
      let materialQuality = this.subProduct[i].materialQuality
      console.log(drawingNumber)
      console.log(productName)
      console.log(materialQuality)

      if (drawingNumber.indexOf(' ') >= 0) {
        this.$message('图号' + drawingNumber + '包含空格')
        return
      }
      if (productName.indexOf(' ') >= 0) {
        this.$message('品名' + productName + '包含空格')
        return
      }
      if (materialQuality.indexOf(' ') >= 0) {
        this.$message('材质' + materialQuality + '包含空格')
        return
      }
    }

    if (paramValid) {
      this.submitProducts()
    }
  }
  async submitProducts() {
    let res = await designProduct({ productList: this.subProduct, noticeId: this.choosedNotice.noticeId }).catch((err: any) => {
      Notification.error(err)
    })
    if (res) {
      Message.success('保存成功')
      this.isEditing = false
      this.showNoticeDetail(this.choosedNotice, this.choosedNoticeIndex)
    }
  }

  /**
   * 点击添加按钮
   * 为产品添加子产品
   */
  addProduct(product) {
    // 需要绑定不同的producingId
    let now = new Date()
    let id = now.getMilliseconds() + now.getSeconds() * 1000 + now.getMinutes() * 100000
    now.getFullYear
    let newProduct = {
      sequenceId: '',
      producingId: -id,
      parentId: product.producingId,
      noticeId: product.noticeId,
      drawingNumber: '',
      productName: '',
      materialQuality: '',
      number: product.number,
      deliveryDate: product.deliveryDate,
      state: '工艺设计',
      remark: '',
      typeProduct: '加工'
    }
    for (let i = 0; i < this.pageProductList.length; i++) {
      if (this.pageProductList[i].producingId == product.producingId) {
        this.pageProductList[i].children.splice(this.pageProductList[i].children.length, 0, newProduct)
        break
      }
    }
  }

  /**
   * 点击复制按钮
   * 将子产品复制到另一个产品下
   */
  copyChildren(product) {
    console.log(product.children)
    this.$prompt('请输入目标产品序列号', `复制子产品路线${product.drawingNumber}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then((e: any) => {
        console.log('点击了确定')
        console.log('目标产品序列号' + e)
        console.log(e)
        let bingo = false
        let preSequenceId = product.sequenceId
        console.log('preSequenceId' + preSequenceId)
        for (let i = 0; i < this.pageProductList.length; i++) {
          console.log('current sequenceId is ' + this.pageProductList[i].sequenceId)
          if (e.value == this.pageProductList[i].sequenceId) {
            console.log('匹配了')
            // 产品匹配
            bingo = true
            // 复制产品
            // 深度复制子产品并修改ID
            console.log('product.children')
            console.log(product.children)
            let newChildren = _.cloneDeep(product.children)
            console.log('newChildren')
            console.log(newChildren)
            for (let k = 0; k < newChildren.length; k++) {
              console.log('处理克隆数组：' + k)
              let now = new Date()
              let id = k + now.getMilliseconds() + now.getSeconds() * 1000 + now.getMinutes() * 100000
              console.log('new ID is ' + -id)
              newChildren[k].producingId = -id
              newChildren[k].parentId = this.pageProductList[i].producingId
              let index = newChildren[k].sequenceId.indexOf('-')
              console.log('index of - ' + index)
              newChildren[k].sequenceId = e.value + newChildren[k].sequenceId.substring(index)
              console.log('new sequenceID is ' + newChildren[k].sequenceId)
            }
            console.log('处理后的newchildren')
            console.log(newChildren)
            console.log('product.children')
            console.log(product.children)
            // 将处理后的子产品路线加入目标产品中
            this.pageProductList[i].children = this.pageProductList[i].children.concat(newChildren)
            break
          }
        }
        console.log(bingo)
        if (bingo == true) {
          this.$message.success('复制成功')
        } else {
          this.$message.error('未匹配到产品')
        }
      })
      .catch(() => {
        console.log('点击了取消')
      })
  }

  /**
   * 点击删除按钮
   * 删除子产品
   */
  deleteProduct(product) {
    // TODO 判断可否删除 不能删除的产品一行不显示删除按钮
    console.log('DELETE PRODUCT')
    console.log(product)
    console.log('pageProductList')
    console.log(this.pageProductList)
    for (let i = 0; i < this.pageProductList.length; i++) {
      console.log('pageProductList BL ' + i)
      console.log(this.pageProductList[i])
      console.log(this.pageProductList[i].producingId)
      if (this.pageProductList[i].producingId == product.parentId) {
        console.log('pageProductList BL ' + i + ' PP')
        console.log(this.pageProductList[i].children)
        for (let j = 0; j < this.pageProductList[i].children.length; j++) {
          if (product.producingId == this.pageProductList[i].children[j].producingId) {
            this.pageProductList[i].children.splice(j, 1)
            break
          }
        }
        break
      }
    }
  }

  // 设计工艺表
  onClickDesign(product, type: any) {
    this.setDesignRowId(this.bindRowId(product))
    console.log('绑定的行ID' + this.designRowId)
    let tempProduct = {
      producingId: product.producingId,
      drawingNumber: product.drawingNumber,
      productName: product.productName,
      materialQuality: product.materialQuality,
      number: product.number,
      remark: product.remark
    }
    console.log(tempProduct.remark)

    this.$store.commit('TwoProcess/SET_PRODUCT_ON_DESIGN_VERSION', tempProduct)
    console.log('设计工艺表绑定对应产品')
    console.log(this.productOnDesignVersion)

    this.$router.push({ name: 'process-route-design', params: { product, type } })
  }

  // 查看产品派工情况
  showDispatch(row) {
    // 携带图号参数跳转至路线单列表页面
    console.log(row)
    console.log(row.drawingNumber)
    this.$router.push({
      name: 'menuA1DispatchForm',
      params: {
        from: 'notice',
        drawingNumber: row.drawingNumber
      }
    })
  }

  /**
   * 双击查看设计详情
   */
  showProcessDetail(row) {
    this.onClickDesign(row, '双击查看详情')
  }

  tableRowClassName({ row, rowIndex }) {
    if (row.parentId == 0) {
      return 'success-row'
    }

    return ''
  }
  tableCellClassName({ row, column, rowIndex, columnIndex }) {
    if (columnIndex == 0 && row.state == '工艺设计') {
      return 'design-row'
    }
    return ''
  }
  /**
 * 点击导出按钮，导出通知单文档
 */
  async exportNotice() {
    var url = '/notice/export?noticeId='
    window.open(url + this.choosedNotice.noticeId)
  }

  // // 通知单卡片区域DIV
  // domObj: any = {}
  // mounted() {
  //   this.bindScrollFunction()
  // }
  // /**
  //  * 鼠标滚轮控制通知单卡片区域横向滚动
  //  */
  // bindScrollFunction() {
  //   this.domObj = document.getElementById('noticeCardsPanel') // 通过id获取要设置的div
  //   if (this.domObj.attachEvent) {
  //     // IE
  //     this.domObj.attachEvent('onmousewheel', this.mouseScrollX)
  //   } else if (this.domObj.addEventListener) {
  //     this.domObj.addEventListener('DOMMouseScroll', this.mouseScrollX, false)
  //   }
  //   this.domObj.onmousewheel = this.domObj.onmousewheel = this.mouseScrollX
  // }

  // mouseScrollX(event) {
  //   let detail = event.wheelDelta || event.detail
  //   let moveForwardStep = -1
  //   let moveBackStep = 1
  //   let step = 0
  //   step = detail > 0 ? moveForwardStep * 100 : moveBackStep * 100
  //   event.preventDefault() // 阻止浏览器默认事件
  //   this.domObj.scrollRight = this.domObj.scrollRight + step
  // }
}
</script>

<style lang="scss" scoped>
// 通知单卡片区域
.notice-cards-panel {
  display: -webkit-box;
  overflow-x: auto;

  .notice-card {
    float: left;
    width: 160px;
    color: #000;
    height: 185px;
    line-height: 25px;
    text-align: center;
    margin-right: 30px;
    margin-bottom: 10px;
    border: 1px solid #ccc;

    .text {
      letter-spacing: 2px;
      font-size: 14px;
      color: #000;
    }
  }

  .notice-card:hover {
    cursor: pointer;
  }
}

// .parent-row {
//   background: #f0f9eb;
// }
// /deep/ .el-table .warning-row {
//     background: oldlace;
//   }

/**************************** */
.total {
  .total_title {
    width: 100px;
    color: #000;
    height: 260px;
    line-height: 30px;
    text-align: center;
  }

  &:hover {
    color: #000;
    background: #fff;
  }
}

.s2 {
  height: 100px;
  display: none;
}

.breadcrumb {
  margin: 10px 0 15px 5px;
  width: 100%;
  border: none;
}

// /*隐藏掉滚动条*/
// .notice-cards-panel::-webkit-scrollbar {
//   display: none;
// }

.layout .operation {
  overflow-x: auto;
}

.el-tabs {
  padding: 0 20px;
  margin: 0px 10px 0;
  border: 1px solid #e4e7ed;
  background-color: #fff;

  .el-tabs__content {
    min-width: 1200px;
  }
}
</style>
